using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace WB.Mvc.Forms.Widgets
{
	public class RadioButtonList : Widget
	{
		private readonly IList<IListItem> listItems = new List<IListItem>();

		public RadioButtonList(string name) : base(name, new Dictionary<string, object>{ { "class", "radio-button-list" } })
		{
		}

		public RadioButtonList(string name, IDictionary<string, object> attributes) : base(name, attributes)
		{
		}

		public IList<IListItem> ListItems { get { return listItems; } }

		public override string ToHtml()
		{
			var element = new XElement("ul");

			var radioElements = ListItems.Select(
				item =>
					{
						var ele = new XElement("input", 
							new XAttribute("type", "radio"), 
							new XAttribute("value", item.Value), 
							new XAttribute("name", Name), 
							new XAttribute("id", Name), item.Text);

						if (Value.Equals(item.Value))
						{
							ele.SetAttributeValue("checked", true);
						}
						return ele;
					}).ToList();

			if (Value.Equals(string.Empty))
			{
				var radioElement = radioElements.First();
				radioElement.SetAttributeValue("checked", true);
			}

			element.Add(radioElements);
			
			foreach (var attrib in Attributes)
			{
				element.SetAttributeValue(attrib.Key, attrib.Value);
			}

			return element.ToString();
		}
	}
}